package com.yh.controller.api;

import com.yh.anno.LoginAuthentication;
import com.yh.service.OrderService;
import com.yh.utils.Constants;
import com.yh.vo.OrderVO;
import com.yh.vo.ResponseVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author yuhuan
 * @date 2022/01/13
 */
@RestController
@RequestMapping("/api/order")
public class OrderWeb {
    @DubboReference(check = false)
    private OrderService orderService;

    /**
     * 根据订单ID查询订单详情(订单实体，影片实体，场次详情)
     * 服务地址 http://localhost:8080/api/order/detail/id
     */
    @RequestMapping("/detail/id")
    @LoginAuthentication
    public ResponseVO findOrderDetailById(String orderId) {
        OrderVO orderVO = orderService.findOrderDetailById(orderId);
        return ObjectUtils.isEmpty(orderVO) ?
                ResponseVO.buildSuccessInstance(Constants.ResponseDataState.NULL_RESULT) :
                ResponseVO.buildSuccessInstance(orderVO);
    }

    /**
     * 根据用户ID查询所有的订单详情
     * 服务地址 http://localhost:8080/api/order/detail/userId
     */
    @RequestMapping("/detail/userId")
    @LoginAuthentication
    public ResponseVO findOrderDetailByUserId(String userId) {
        List<OrderVO> orderVOList = orderService.findOrderDetailByUserId(userId);
        return ObjectUtils.isEmpty(orderVOList) ?
                ResponseVO.buildSuccessInstance(Constants.ResponseDataState.NULL_RESULT) :
                ResponseVO.buildSuccessInstance(orderVOList);
    }

    /**
     * 创建订单
     * 服务地址 http://localhost:8080/api/order/create
     */
    @RequestMapping("create")
    @LoginAuthentication
    public ResponseVO createOrder(@RequestBody OrderVO orderVo) {
        OrderVO orderVO = orderService.createOrder(orderVo);
        // 如果订单创建成功，则添加支付地址并响应成功
        if (orderVO.getCreateState()) {
            orderVO.setPayUrl("pay.html");
            return ResponseVO.buildSuccessInstance(orderVO);
        }
        return ResponseVO.buildSuccessInstance(Constants.ResponseDataState.FAILURE_ORDER);
    }

    /**
     * 根据订单ID删除订单（将订单标记为删除，不会从数据库真正的移除订单信息）
     * 服务地址 http://localhost:8080/api/order/delete
     */
    @RequestMapping("delete")
    @LoginAuthentication
    public ResponseVO deleteOrderById(String orderId) {
        int respState = orderService.deleteOrderById(orderId);
        return ResponseVO.buildSuccessInstance(respState);
    }


    /**
     * 删除过期订单并释放过期订单占用的座位
     * 服务地址 http://localhost:8080/api/order/release/seat
     */
    @RequestMapping("/release/seat")
    public ResponseVO releaseSeat() {
        orderService.checkExpiredOrder();
        ResponseVO.InstanceBuild instanceBuild = new ResponseVO.InstanceBuild();
        return instanceBuild.setCode(200).setMsg("OK").build();
    }
}
